/**
 *  ControlFlowGraph.java : IceBird project
 *  23:52:51 
 */
package icebird.compiler.bytecode;

import icebird.utils.ObjectArrayIterator;

import java.util.Iterator;

/**
 * @author Sergey Shulepoff[Knott]
 */
public final class ControlFlowGraph implements Iterable<BasicBlock> {
	
	private byte[] opcode;
	private BasicBlock[] blocks;
	
	
	public ControlFlowGraph(ByteCode bc) {
		BasicBlockFinder find = new BasicBlockFinder();
		
		BytecodeParser parser = new BytecodeParser(bc, find);
		parser.parse();
		parser = null;
		
		blocks = find.createBasicBlocks();
		opcode = find.getOpcodeFlags();
	}
	
	public int getCount() {
		return blocks.length;
	}
	
	public BasicBlock getBasicBlock(int pc) {
		final int max = blocks.length;
		for (int i = 0; i < max; i++) {
			final BasicBlock bb = blocks[i];
			if (bb.contains(pc)) {
				return bb;
			}
		}
		return null;
	}
	
	
	
	public final boolean isOpcodeFlagSet(int address, int mask) {
		return ((opcode[address] & mask) == mask);
	}
	
	public final int getOpcodeFlags(int address) {
		return opcode[address];
	}

	public Iterator<BasicBlock> iterator() {
		return new ObjectArrayIterator<BasicBlock>(blocks);
	}
	
	
}
